package com.fenquen.sourceguard.repack;

import com.fenquen.sourceguard.repack.util.StringUtils;
import org.apache.commons.cli.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class BootstrapRepack {


    private static final String ORIGIN_JAR_PATH = "origin_jar_path";
    private static final String ENCRYPTED_JAR_PATH = "encrypted_jar_path";
    private static final String PACKAGE_OR_CLASS_NAMES = "package_or_class_names";
    private static final String BIND_MACHINE = "bind_machine";

    public static void main(String[] args) throws Exception {

        Options options = new Options();

        Option optionOriginJarPath = new Option(ORIGIN_JAR_PATH, true, "the path of the jar which need to be encrypted");
        optionOriginJarPath.setRequired(true);
        options.addOption(optionOriginJarPath);

        Option optionEncryptedJarPath = new Option(ENCRYPTED_JAR_PATH, true, "mandatory designated path where the encrypted jar would generate");
        optionEncryptedJarPath.setRequired(false);
        options.addOption(optionEncryptedJarPath);

        Option optionPackageOrClassNames = new Option(PACKAGE_OR_CLASS_NAMES, true, "comma separated string");
        optionPackageOrClassNames.setRequired(true);
        options.addOption(optionPackageOrClassNames);

        Option optionBindMachine = new Option(BIND_MACHINE, true, "bind machine");
        optionBindMachine.setRequired(false);
        options.addOption(optionBindMachine);

        CommandLineParser commandLineParser = new DefaultParser();

        CommandLine commandLine = commandLineParser.parse(options, args);

        String originJarPath = commandLine.getOptionValue(ORIGIN_JAR_PATH);
        String encryptedJarPath = commandLine.getOptionValue(ENCRYPTED_JAR_PATH);

        String basePackageOrClassNames = commandLine.getOptionValue(PACKAGE_OR_CLASS_NAMES);
        basePackageOrClassNames += ",org.springframework.asm.ClassReader,org.springframework.cglib.core.AbstractClassGenerator";
        List<String> basePackageOrClassNameList = Arrays.stream(basePackageOrClassNames.split(",")).
                collect(Collectors.toList());

        Repackager.bindMachine = "y".equals(commandLine.getOptionValue(BIND_MACHINE, "n"));

        if (StringUtils.isBlank(encryptedJarPath)) {
            Repackager.encryptJar(originJarPath, basePackageOrClassNameList);
        } else {
            Repackager.encryptJar(originJarPath, encryptedJarPath, basePackageOrClassNameList);
        }
    }

}
